<?php
Yii::import('ext.feed.*');
class UsersController extends Controller
{
	public $layout='//layouts/main';

	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

  public function actions(){
    return array(
        'captcha'=>array(
            'class'=>'CaptchaExtendedAction',
        ),
    );
  }

	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view', 'new', 'update', 'create', 'school', 'cciht', 'activities', 'cec', 'cedp', 'accreditation', 'efl', 'extend', 'captcha'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
    
  public function actionExtend(){
    // check if there's invoice records
    $invoice = Invoices::model()->find('user_id = :user_id AND status = 0', array(':user_id' => $_SESSION['id']));
  
    if($invoice){
      $this->redirect(bu("invoices/"));
    }else{
      $user = Users::model()->find('id = :id', array(':id' => $_SESSION['id']));
      $school = School::model()->find('user_id = :user_id', array(':user_id' => $user->id));
      $related_schools = School::model()->findAll('name = :name AND address = :address AND city = :city', array(':name' => $school->name, ':address' => $school->address, ':city' => $school->city));
      
      $this->render('extend', array(
        'user' => $user,
        'school' => $school,
        'related_schools' => $related_schools,
      ));
    }
  }
  
  public function actionInvoice(){
  
  }

	//school member
	public function actionCreate()
	{
    if(isset($_POST['Users']))
    {
      $valid = new Users;
      $valid->attributes = $_POST['Users'];
      $valid->attributes = $_POST['info'];
      
      // print_r($_POST['info']['newsletter']);

      if($valid->validate('valid')){
        $school_info = $_POST['info'];
        $user_info = $_POST['Users'];

        // create school member
        $count =0;
        $flag = '';

        if($_POST['check']['kindergarten'] == 'true'){
          $kindergarten = $_POST['kindergarten'];
          $flag = 'K';
          $school_type = 'Kindergarten';
          $count++;

          School::model()->makeMemberSchool($user_info, $school_info, $kindergarten, $flag, $school_type);
        }

        if($_POST['check']['primary'] == 'true'){
          $primary = $_POST['primary'];
          $flag = 'E';
          $school_type = 'Elementary';
          $count++;

          School::model()->makeMemberSchool($user_info, $school_info, $primary, $flag, $school_type);
        }

        if($_POST['check']['junior'] == 'true'){
          $junior = $_POST['junior_school'];
          $flag = 'JH';
          $school_type = 'Junior High School';
          $count++;

          School::model()->makeMemberSchool($user_info, $school_info, $junior, $flag, $school_type);
        }

        if($_POST['check']['senior'] == 'true'){
          $senior = $_POST['senior_school'];
          $flag = 'SH';
          $school_type = 'Senior High School';
          $count++;

          School::model()->makeMemberSchool($user_info, $school_info, $senior, $flag, $school_type);
        }

        //print_r($folder.$user->id);

        Yii::app()->user->setFlash('success', 'Success');
        Yii::app()->user->setFlash('content', 'You have successfully registered as school member. Please wait for our confirmation email.');
        $this->redirect(bu("/?notif=register_successfull"));
      }
    }

    $error_messages = $user->getErrors();
    $user->password = '';

    $this->render('new', array(
      'user' => $user,
      'error_messages' => $error_messages,
    ));
    //*/
	}

  public function actionUpdate(){
    if(isset($_POST['Users']))
    {
      $valid = Users::model()->find('id = :id', array(':id' => $_SESSION['id']));
      $valid->attributes = $_POST['Users'];
      $valid->attributes = $_POST['info'];
      
      // print_r($_POST['info']['newsletter']);

      if($valid->validate('valid')){
        $school_info = $_POST['info'];
        $user_info = $_POST['Users'];

        // create school member
        $count =0;
        $flag = '';

        if($_POST['check']['kindergarten'] == 'true'){
          $kindergarten = $_POST['kindergarten'];
          $flag = 'K';
          $school_type = 'Kindergarten';
          $count++;
          
          // search if school is existed or not, if not make one
          $search = School::model()->find('school_type = :school_type AND name = :name', array(':school_type' => $school_type, ':name' => $school_info['name']));
          if($search){
            School::model()->updateMemberSchool($user_info, $school_info, $kindergarten, $flag, $school_type);
          }else{
            School::model()->makeMemberSchool($user_info, $school_info, $kindergarten, $flag, $school_type);
          }
        }

        if($_POST['check']['primary'] == 'true'){
          $primary = $_POST['primary'];
          $flag = 'E';
          $school_type = 'Elementary';
          $count++;

          // search if school is existed or not, if not make one
          $search = School::model()->find('school_type = :school_type AND name = :name', array(':school_type' => $school_type, ':name' => $school_info['name']));
          if($search){
            School::model()->updateMemberSchool($user_info, $school_info, $primary, $flag, $school_type);
          }else{
            School::model()->makeMemberSchool($user_info, $school_info, $primary, $flag, $school_type);
          }
        }

        if($_POST['check']['junior'] == 'true'){
          $junior = $_POST['junior_school'];
          $flag = 'JH';
          $school_type = 'Junior High School';
          $count++;

          // search if school is existed or not, if not make one
          $search = School::model()->find('school_type = :school_type AND name = :name', array(':school_type' => $school_type, ':name' => $school_info['name']));
          if($search){
            School::model()->updateMemberSchool($user_info, $school_info, $junior, $flag, $school_type);
          }else{
            School::model()->makeMemberSchool($user_info, $school_info, $junior, $flag, $school_type);
          }
        }

        if($_POST['check']['senior'] == 'true'){
          $senior = $_POST['senior_school'];
          $flag = 'SH';
          $school_type = 'Senior High School';
          $count++;

          // search if school is existed or not, if not make one
          $search = School::model()->find('school_type = :school_type AND name = :name', array(':school_type' => $school_type, ':name' => $school_info['name']));
          if($search){
            School::model()->updateMemberSchool($user_info, $school_info, $senior, $flag, $school_type);
          }else{
            School::model()->makeMemberSchool($user_info, $school_info, $senior, $flag, $school_type);
          }
        }

        //print_r($folder.$user->id);

        Yii::app()->user->setFlash('success', 'Success');
        Yii::app()->user->setFlash('content', 'You have successfully update your data.');
        
        $this->redirect(bu("invoices/"));
      }
    }
  }
  
  public function actionNew()
  {
    $user = new Users;
    $user->member_id = 1;
    $this->render('new', array(
        'user' => $user,
    ));
  }

  public function actionCciht()
  {
    $info = $_POST['Cciht'];
    $delivery_type="";

    for($a=0;$a<4;$a++)
    {
      if(isset($info['delivery_type'][$a]))
      {
        $delivery_type=$info['delivery_type'][$a].'|'.$delivery_type;
      }
    }

    $cciht = new Cciht;
    $cciht->attributes = $info;

    if($info['name']){
      $cciht->name = $info['nick'].'. '.$info['name'];
    }
    $cciht->email = $info['email'];

    $tmp = '';

    if($info['delivery_type']){
     foreach ($info['delivery_type'] as $type)
     {
       $tmp = $type.'<br />'.$tmp;
     }
     $cciht->delivery_type = $tmp;
    }

    if($cciht->save())
    {
      Yii::app()->user->setFlash('success', 'Success');
      Yii::app()->user->setFlash('content', 'You have successfully register as CCIHT Members.');

      $this->redirect(bu('/'));
    }
    $cciht->name=$info['name'];
    $cciht->delivery_type = $info['delivery_type'];

    Yii::app()->user->setFlash('error', 'Error');
    Yii::app()->user->setFlash('content', 'There are errors occured, Please check your fields.');

    $this->render('/programs/cciht',array(
      'model' => $cciht,
    ));
  }
  
  public function actionActivities(){
    $data = $_POST['Activities'];
    
    if(isset($_POST['student'])){
      $students = $_POST['student'];
    }
    
    if(isset($_POST['mentor'])){
      $mentors = $_POST['mentor'];
    }
    
    $error = false;

    $activities = new Activities;
    $activities->attributes = $data;

    if($activities->save()){
      // students
      for($a = 1; $a <= count($students); $a++){
        $detail = new ActivitiesDetail;
        $detail->attributes = $students[$a];
        $detail->position = 'Student';
        $detail->activity_id = $activities->id;
        $detail->coupon_code = md5($detail->name.$activities->id);
        
        if($detail->validate('student')){
          $detail->save('student');
        }else{
          $error = true;
        }
      }
      
      // mentors
      for($a = 1; $a <= count($mentors); $a++){
        $detail = new ActivitiesDetail;
        $detail->attributes = $mentors[$a];
        $detail->position = 'Mentor';
        $detail->activity_id = $activities->id;
        $detail->coupon_code = md5($detail->name.$activities->id);
        
        if($detail->validate('mentor')){
          $detail->save('mentor');
        }else{
          $error = true;
        }
      }
      // send email to administrator
      
      // set used variable
      $program = Programs::model()->find('id = :id', array(':id' => 4));
      $model = $activities;
      $fields = array_keys($activities->attributes);
      $details = ActivitiesDetail::model()->findAll('activity_id = :id', array(':id' => $model->id));
      
      $email = Yii::app()->email;
      $email->to = 'edprogram@acsi.or.id';
      $email->subject = 'ACSI - '.$activities->institution_name.' Member Registration (SELC)';
      $email->view = 'activities';
      $email->viewVars = array('program' => $program,
			'model' => $model,
      'fields' => $fields,
      'details' => $details,);
      $email->send();
    
      Yii::app()->user->setFlash('success', 'Success');
      Yii::app()->user->setFlash('content', 'You have successfully register as SELC Member.');

      $this->redirect(bu('/'));
    }
    // */

    Yii::app()->user->setFlash('error', 'Error');
    Yii::app()->user->setFlash('content', 'There are errors occured, Please check your fields.');

    $this->render('/programs/activities',array(
      'model' => $activities,
    ));
  }
  
  public function actionEfl(){
    $data = $_POST['Efl'];

    $efl = new Efl;
    $efl->attributes = $data;

    if($efl->save()){
			// send email to admin
			$program = Programs::model()->find('id = :id', array(':id' => 4));
      $model = $efl;
      $fields = array_keys($efl->attributes);
		
			$email = Yii::app()->email;
      $email->to = 'dir-acd-services@acsi.or.id';
      $email->subject = 'ACSI - '.$efl->name.' Member Registration (EFL)';
      $email->view = 'efl';
      $email->viewVars = array('program' => $program,
			'model' => $model,
      'fields' => $fields,);
      $email->send();
		
      Yii::app()->user->setFlash('success', 'Success');
      Yii::app()->user->setFlash('content', 'You have successfully register as EFL Member.');

      $this->redirect(bu('/'));
    }

    Yii::app()->user->setFlash('error', 'Error');
    Yii::app()->user->setFlash('content', 'There are errors occured, Please check your fields.');

    $this->render('/programs/efl',array(
      'model' => $efl,
    ));
  }

  public function actionCedp(){
    $data = $_POST['Cedp'];

    $cedp = new Cedp;
    $cedp->attributes = $data;

    if($cedp->save()){
      Yii::app()->user->setFlash('success', 'Success');
      Yii::app()->user->setFlash('content', 'You have successfully register as CEDP Member.');

      $this->redirect(bu('/'));
    }

    Yii::app()->user->setFlash('error', 'Error');
    Yii::app()->user->setFlash('content', 'There are errors occured, Please check your fields.');

    $this->render('/programs/cedp',array(
      'model' => $cedp,
    ));
  }

  public function actionCec(){
    $data = $_POST['Cec'];

    $cec = new Cec;
    $cec->attributes = $data;
    
    $cec->photo=CUploadedFile::getInstance($cec,'uploadedFile');
    
    // $this->performAjaxValidation($cec);

    if($cec->save()){
      $folder=Yii::getPathOfAlias('webroot.assets.users.Cec').DIRECTORY_SEPARATOR;
      
      if($cec->photo){
        $cec->photo->saveAs($folder.$cec->photo);
      }
    
      Yii::app()->user->setFlash('success', 'Success');
      Yii::app()->user->setFlash('content', 'You have successfully register as CEC Member.');

      $this->redirect(bu('/'));
    }

    $this->render('/programs/cec', array(
      'model' => $cec,
    ));
  }

  public function actionAccreditation()
  {
    $info = $_POST['Accreditation'];
    $accreditation = new Accreditation;

    $accreditation->attributes = $info;

    $accreditation->email = $info['email'];
    $accreditation->accreditation_early_education = $info['early_from'].'-'.$info['early_current'];
    $accreditation->accreditation_elementary = $info['elementary_from'].'-'.$info['elementary_to'];
    $accreditation->accreditation_secondary = $info['secondary_from'].'-'.$info['secondary_to'];
    $accreditation->accredited_date_granted = $info['currently_from'].'-'.$info['currently_to'];
    $accreditation->accredited_grades= $info['grades_from'].'-'.$info['grades_to'];

    if(isset($info['whom'])){
      if($info['whom'] != ''){
        $accreditation->joint_accreditation_planned = $info['joint_accreditation_planned'].', '.$info['whom'];
      }
    }

    if($accreditation->save())
    {
      Yii::app()->user->setFlash('success', 'Success');
      Yii::app()->user->setFlash('content', 'You have successfully register as Accreditation Member.');

      $this->redirect(bu('/'));
    }

    $accreditation->early_from = $info['early_from'];
    $accreditation->early_current = $info['early_current'];
    $accreditation->elementary_from = $info['elementary_from'];
    $accreditation->elementary_to = $info['elementary_to'];
    $accreditation->secondary_from = $info['secondary_from'];
    $accreditation->secondary_to = $info['secondary_to'];
    $accreditation->currently_from = $info['currently_from'];
    $accreditation->currently_to = $info['currently_to'];
    $accreditation->grades_from = $info['grades_from'];
    $accreditation->grades_to = $info['grades_to'];

    Yii::app()->user->setFlash('error', 'Error');
    Yii::app()->user->setFlash('content', 'Register failed. Please try again.');

    $this->render('/programs/accreditation',array(
      'model' => $accreditation,
    ));
		//*/
  }

  public function actionSchool()
  {
    $user = new Users;
    $user->member_id = 2;
    $this->render('school', array(
      'user' => $user,
    ));
  }

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Users::model()->findByPk((int)$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='users-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
